package bakenote.xml;


import bakenote.core.Recipe;
import bakenote.core.RecipeGroup;
import bakenote.data.RecipeGroupList;
import org.apache.pivot.collections.List;
import org.apache.pivot.xml.Element;
import org.apache.pivot.xml.TextNode;
import org.apache.pivot.xml.XMLSerializer;
import sun.plugin.dom.core.Text;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;


public class GroupXMLWriter {

    private static XMLSerializer xmlSerializer = new XMLSerializer();

    private GroupXMLWriter() {
    }

    private static Element groupXML(RecipeGroup group) {

        Element groupElement = new Element("group");
        Element nameElement = new Element("name");
        TextNode textNode = new TextNode(group.getName());
        nameElement.add(textNode);
        Element uuidElement = new Element("uuid");
        textNode = new TextNode(group.getUUID());
        uuidElement.add(textNode);

        Element recipesElement = new Element("recipes");
        for (Recipe r: group.getList()) {
            uuidElement = new Element("uuid");
            textNode = new TextNode(r.getUUID());
            uuidElement.add(textNode);
            recipesElement.add(uuidElement);
        }

        groupElement.add(nameElement);
        groupElement.add(uuidElement);
        groupElement.add(recipesElement);

        return groupElement;
    }

    public static void writeXML(List<RecipeGroup> groupList, File xmlFile) throws Exception {

        Element recipeBook = new Element("recipebook");
        for (RecipeGroup g: groupList) {
            recipeBook.add(groupXML(g));
        }

        // Write the recipeBook to a stringWriter for later indentation
        StringWriter stringWriter = new StringWriter();
        xmlSerializer.writeObject(recipeBook, stringWriter);

        // Apply indentation to the stringWriter
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        StringWriter indentedStringWriter = new StringWriter();
        transformer.transform(new StreamSource(new StringReader(stringWriter.toString())), new StreamResult(indentedStringWriter));
        // Save the xml element to a file
        FileWriter fw = new FileWriter(xmlFile, true);
        fw.write(indentedStringWriter.toString());
        fw.flush();
        fw.close();

    }
}
